import React, { useEffect, useMemo } from "react";
import { Modal } from "../Modal/Modal";
import { Button } from "../components/form/Button/Button";
import styles from "./HistoryModal.module.css";
import { useChat } from "../../store/useChat";
import { useHistoryModal } from "../../store/useHistoryModal";
import { useModal } from "../../store/useModal";
import { formatTime } from "../../../util/time";
import clsx from "clsx";

const HistoryDialog: React.FC = () => {
    const conversations = useChat((state) => state.conversations);
    const deleteConversion = useChat((state) => state.deleteConversation);
    const clearConversation = useChat((state) => state.clearConversations);
    const isHydrated = useChat((state) => state.isHydrated);
    const currentConversationId = useChat(
        (state) => state.currentConversationId,
    );
    const setCurrentConversationId = useChat(
        (state) => state.setCurrentConversationId,
    );
    const init = useChat((state) => state.initialize);

    const isHistoryModalOpen = useHistoryModal((state) => state.isOpen);
    const toggleHistoryModal = useHistoryModal((state) => state.toggle);

    const confirm = useModal((state) => state.confirm);
    const list = useMemo(() => {
        return conversations.map((conversation, index) => {
            const updateTime = formatTime(conversation.updatedAt);
            const isCurrent = conversation.id === currentConversationId;
            const itemClx = clsx([
                styles.historyItem,
                isCurrent && styles.active,
            ]);
            return (
                <li key={conversation.id} className={itemClx}>
                    <div className={styles.conversationInfo}>
                        <span className={styles.conversationTitle}>
                            {index + 1 + " " + conversation.title}
                        </span>
                        <span className={styles.conversationTime}>
                            {updateTime}
                        </span>
                    </div>
                    <Button
                        size="small"
                        onClick={handleSelect.bind(null, conversation.id)}
                    >
                        选择
                    </Button>
                    <Button
                        size="small"
                        variant="danger"
                        onClick={() => handleDelete(conversation.id)}
                    >
                        删除
                    </Button>
                </li>
            );
        });
    }, [conversations]);
    // 初始化对话
    useEffect(() => {
        init();
    }, [isHydrated]);
    if (!isHydrated) {
        return null;
    }
    // 删除对话
    function handleDelete(id: string) {
        confirm({
            title: "删除对话",
            content: "确定删除该对话？",
            onOK: async () => {
                deleteConversion(id);
            },
        });
    }

    function handleSelect(id: string) {
        setCurrentConversationId(id);
        toggleHistoryModal();
    }

    // 清空所有对话
    function handleClearAll() {
        confirm({
            title: "清空对话",
            content: "确定清空所有对话？",
            onOK: async () => {
                clearConversation();
            },
        });
    }
    return (
        <Modal
            isOpen={isHistoryModalOpen}
            onClose={toggleHistoryModal}
            title="历史对话"
        >
            <div className={styles.historyList}>
                {conversations.length === 0 ? (
                    <p className={styles.emptyMessage}>暂无历史对话</p>
                ) : (
                    <ul>{list}</ul>
                )}
            </div>
            <div className={styles.footerControls}>
                {conversations.length > 0 && (
                    <Button variant="danger" onClick={handleClearAll}>
                        清空所有
                    </Button>
                )}
                <Button variant="primary" onClick={toggleHistoryModal}>
                    关闭
                </Button>
            </div>
        </Modal>
    );
};

export default HistoryDialog;
